# Common Library for Widget Classes

import wx

def getDomAttr(dom, attr_name, default_value=""):
    value = dom.getAttribute(attr_name)
    if value == "": return default_value
    else: return value

def setPosTuple(pos_x, pos_y):
    try:
        x = int(pos_x)
        y = int(pos_y)
    except:
        (x, y) = wx.DefaultPosition

    # TODO: one among two value (x,y) can be a negative value
    if x < 0 or y < 0: return wx.DefaultPosition
    else: return (x, y)

def setSizeTuple(size_width, size_height):
    if size_width == "": size_width = -1
    if size_height == "": size_height = -1
    
    try:
        width = int(size_width)
        height = int(size_height)
    except:
        (width, height) = wx.DefaultSize
        
    if width < 0: width = -1
    if height < 0: height = -1
    
    return (width, height)

def findFirstMatchedAncestor(meta_widget, stopping_point):
    parent_node = meta_widget.getParentMetaWidget()
    while parent_node:
        widget_object = parent_node.getWidget()
        class_name = widget_object.__class__.__name__
        if class_name in stopping_point:
            return widget_object
        
        parent_node = parent_node.getParentMetaWidget()
        
    return None

def stringToInteger(value):
    try:
        return int(value)
    except:
        return None

def getPosParam(dom):
    x = dom.getAttribute("x")
    y = dom.getAttribute("y")
    
    return setPosTuple(x, y)   

def getSizeParam(dom):
    width = dom.getAttribute("width")
    height = dom.getAttribute("height")
    
    return setSizeTuple(width, height)


## The followings are new code

def str2int(str, default=0):
    try:
        return int(str)
    except:
        return default
    
def str2bool(str, default=False):
    str = str.lower()
    
    if str == "true": return True
    elif str == "false": return False
    else: return default